package com.jbookshelf.beans;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.jbookshelf.dal.entities.Languages;
import com.jbookshelf.dal.entities.Shops;
import com.jbookshelf.dal.providers.ShopsDataProvider;

@Component
@Scope("request")
public class ShopsBean {
	@Autowired
	ShopsDataProvider dataProvider;

	private List<Shops> shops;
	private Shops selectedShop;

	private Shops newShop = new Shops();

	public List<Shops> getShops() {
		if (shops == null) {
			shops = dataProvider.getShops();
		}
		return shops;
	}

	public void setShops(List<Shops> shops) {
		this.shops = shops;
	}

	public Shops getSelectedShop() {
		return selectedShop;
	}

	public void setSelectedShop(Shops selectedShop) {
		this.selectedShop = selectedShop;
	}

	public Shops getNewShop() {
		return newShop;
	}

	public void setNewShop(Shops newShop) {
		this.newShop = newShop;
	}

	public void showDialog() {
		final RequestContext context = RequestContext.getCurrentInstance();
		context.execute("newShopDialog.show()");

	}

	public void hideDialog() {
		final RequestContext context = RequestContext.getCurrentInstance();
		context.execute("newShopDialog.hide()");
	}

	public void validateName(FacesContext context, UIComponent component,
			Object value) {
		String name = (String) value;
			List<Shops> listshop = dataProvider.getShops();
			for (Shops shop : listshop) {
				if (shop.getName().equals(name)) {
					throw new ValidatorException(new FacesMessage(
							FacesMessage.SEVERITY_ERROR,
							"This shop already is present", null));
				}
			}
	}

	public void saveNewShop() {
		if (newShop.getName().isEmpty()) {
			FacesContext.getCurrentInstance().addMessage(
					"newShopDialog_form:shop_name_str",
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Value is required", null));
			return;
		}
		dataProvider.insertShop(newShop);
		hideDialog();
		RequestContext.getCurrentInstance().update("shops_form");

	}

}
